<template>
    <div class="indicator-container">
        <!-- 顶部导航 -->
        <header class="app-header">
            <!-- Use button like Family.vue -->
            <button class="back-button" @click="router.back()" title="返回">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="header-content">
                 <h1>健康指标分析</h1>
            </div>
            <!-- Placeholder to balance the back button -->
            <div class="header-placeholder"></div>
        </header>

        <!-- 主要内容区域 -->
        <main class="main-content">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载中...</span>
            </div>

            <!-- 指标列表 -->
            <div v-else class="indicators-list">
                <div v-for="(indicator, index) in indicators" 
                     :key="index" 
                     class="indicator-card">
              
                    <div class="indicator-icon" :class="indicator.status">
                        <i :class="indicator.icon"></i>
                    </div>
                    <div class="indicator-info">
                        <div class="indicator-header">
                            <h3>{{ indicator.name }}</h3>
                            <span class="indicator-value" :class="indicator.status">
                                {{ indicator.value }}
                                <small>{{ indicator.unit }}</small>
                            </span>
                        </div>
                        <div class="indicator-details">
                            <div class="trend">
                                <i :class="indicator.trendIcon"></i>
                                <span>{{ indicator.trend }}</span>
                            </div>
                            <div class="status-text" :class="indicator.status">
                                {{ indicator.statusText }}
                            </div>
                        </div>
                    </div>
                    <div class="card-actions">
                        <div class="trend-analysis-btn" @click.stop="viewTrendAnalysis(indicator)">
                            <i class="fas fa-chart-line"></i>
                            <span>数据趋势</span>
                        </div>
                        <div class="indicator-action">
                            <i class="fas fa-chevron-right"></i>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 底部导航 -->
        <nav class="bottom-nav">
            <div class="nav-item" :class="{ active: activeTab === 'home' }" @click="router.push('/home')">
                <i class="fas fa-home"></i>
                <span>首页</span>
            </div>
            <div class="nav-item" :class="{ active: activeTab === 'mine' }" @click="router.push('/Personal')">
                <i class="fas fa-user"></i>
                <span>我的</span>
            </div>
        </nav>
    </div>
</template>

<script>
import { ref, computed, onMounted, reactive, onUnmounted } from 'vue';
import { useRouter } from "vue-router";
import axios from 'axios';
import { getItem } from '@/components/Session.vue';
import websocketService from '@/services/websocket';

export default {
    setup() {
        const router = useRouter();
        const activeTab = ref('home');
        const indicators = ref([]);
        const loading = ref(true);
        const scope = reactive({});
        const user = getItem("user")
        
        const currentDate = computed(() => {
            const date = new Date();
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        });

        // 获取指标数据
        const fetchIndicators = async () => {
            try {
                const response = await axios.get('/api/indicator/select', {
                    params: {
                        username: user.username // 这里应该从用户信息中获取
                    }
                });

                if (response.data.code === 200) {
                    indicators.value = response.data.data.map(item => {
                        // 解析正常范围并存储
                        const [min, max] = item.normalScope.split('-').map(Number);
                        scope[item.indicatorName] = { min, max }; // 使用指标名称作为键
                        
                        const value = Number(item.lastMeasure);
                        
                        // 判断状态
                        let status = 'normal';
                        let statusText = '正常范围';
                        if (value < min) {
                            status = 'warning';
                            statusText = '偏低';
                        } else if (value > max) {
                            status = 'warning';
                            statusText = '偏高';
                        }

                        // 获取对应的图标
                        const iconMap = {
                            '收缩压': 'fas fa-heartbeat',
                            '舒张压': 'fas fa-heartbeat',
                            '血糖': 'fas fa-tint',
                            '心率': 'fas fa-heart',
                            '体温': 'fas fa-thermometer-half'
                        };

                        return {
                            name: item.indicatorName,
                            value: item.lastMeasure,
                            unit: item.indicatorUnit,
                            icon: iconMap[item.indicatorName] || 'fas fa-chart-line',
                            status: status,
                            statusText: statusText,
                        
                            history: `/${item.indicatorName.toLowerCase()}-history`,
                            trendAnalysis: `/selectindex`
                        };
                    });
                } else {
                    console.error('获取指标数据失败:', response.data.message);
                }
            } catch (error) {
                console.error('请求失败:', error);
            } finally {
                loading.value = false;
            }
        };


        const viewTrendAnalysis = (indicator) => {
            router.push({
                path: indicator.trendAnalysis,
                query: {
                    indicator: indicator.name,
                    min: scope[indicator.name].min,
                    max: scope[indicator.name].max
                }
            });
        };

        // 处理 WebSocket 消息的函数
        const handleIndicatorUpdate = (data) => {
            const [indicatorName, value] = data.split(',');
            const index = indicators.value.findIndex(indicator => indicator.name === indicatorName);
            if (index !== -1) {
                indicators.value[index].value = value;
            }
        };

        // 组件挂载时获取数据
        onMounted(() => {
            fetchIndicators();
            // 使用全局 WebSocket 服务
            websocketService.connect('indicator/update', user.username);
            websocketService.addMessageHandler('indicator/update', handleIndicatorUpdate);
        });

        // 组件卸载时清理
        onUnmounted(() => {
            websocketService.removeMessageHandler('indicator/update', handleIndicatorUpdate);
        });

        return {
            currentDate,
            indicators,
            activeTab,
            router,
            loading,
            viewTrendAnalysis
        };
    }
}
</script>

<style scoped>
.indicator-container {
    min-height: 100vh;
    max-width: 100vw;
    width: 100%;
    background-color: #f8f9fa;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow-x: hidden;
}

.app-header {
    background: linear-gradient(135deg, #4CAF50, #2196F3);
    color: white;
    padding: 4vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 100;
}

.back-button {
    background: none;
    border: none;
    color: white;
    font-size: 5vw;
    cursor: pointer;
    padding: 2vw;
    margin-left: -2vw;
    line-height: 1;
}

.back-button:hover {
    opacity: 0.8;
}

.header-content {
    text-align: center;
    flex-grow: 1;
}

.header-content h1 {
    color: white;
    font-size: 4.5vw;
    font-weight: 600;
    margin: 0;
}

.header-placeholder {
    width: 10vw;
    visibility: hidden;
}

.main-content {
    flex: 1;
    padding: 4vw;
    padding-bottom: 20vw;
}

.health-overview {
    background: white;
    border-radius: 3vw;
    padding: 4vw;
    margin-bottom: 4vw;
    box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
}

.overview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 3vw;
}

.overview-header h2 {
    font-size: 4vw;
    margin: 0;
    color: #333;
}

.date {
    font-size: 3vw;
    color: #666;
}

.overview-stats {
    display: flex;
    justify-content: space-around;
    text-align: center;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.stat-value {
    font-size: 6vw;
    font-weight: 600;
    color: #2196F3;
}

.stat-label {
    font-size: 3vw;
    color: #666;
    margin-top: 1vw;
}

.indicators-list {
    display: flex;
    flex-direction: column;
    gap: 3vw;
}

.indicator-card {
    background: white;
    border-radius: 3vw;
    padding: 4vw;
    display: flex;
    align-items: flex-start;
    box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
    cursor: pointer;
    transition: transform 0.2s;
    position: relative;
    margin-bottom: 2vw;
}

.indicator-card:hover {
    transform: translateY(-0.5vw);
}

.indicator-icon {
    width: 12vw;
    height: 12vw;
    border-radius: 2.5vw;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 4vw;
    flex-shrink: 0;
}

.indicator-icon i {
    font-size: 6vw;
}

.indicator-info {
    flex: 1;
    min-width: 0;
    padding-right: 2vw;
}

.indicator-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2vw;
}

.indicator-header h3 {
    margin: 0;
    font-size: 4.5vw;
    color: #333;
    font-weight: 600;
}

.indicator-value {
    font-size: 4.5vw;
    font-weight: 600;
}

.indicator-value small {
    font-size: 2.8vw;
    font-weight: normal;
    color: #666;
    margin-left: 0.5vw;
}

.indicator-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 3.2vw;
    margin-top: 1.5vw;
}

.trend {
    display: flex;
    align-items: center;
    gap: 1vw;
    color: #666;
}

.trend i {
    font-size: 3.2vw;
}

.status-text {
    font-size: 2.8vw;
    padding: 0.8vw 2vw;
    border-radius: 2vw;
}

.card-actions {
    display: flex;
    align-items: center;
    gap: 2vw;
    margin-left: auto;
    margin-top: 3vw;
}

.trend-analysis-btn {
    display: flex;
    align-items: center;
    gap: 1vw;
    background: linear-gradient(135deg, #2196F3, #4CAF50);
    color: white;
    padding: 1.8vw 3.5vw;
    border-radius: 4vw;
    font-size: 2.8vw;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 0.3vw 0.8vw rgba(33, 150, 243, 0.2);
    white-space: nowrap;
}

.trend-analysis-btn i {
    font-size: 2.8vw;
}

.trend-analysis-btn:hover {
    transform: translateY(-0.3vw);
    box-shadow: 0 0.5vw 1vw rgba(33, 150, 243, 0.3);
}

.trend-analysis-btn:active {
    transform: translateY(0);
    box-shadow: 0 0.3vw 0.8vw rgba(33, 150, 243, 0.2);
}

.indicator-action {
    color: #999;
    font-size: 4vw;
    display: flex;
    align-items: center;
}

.bottom-nav {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 15vw;
    background: white;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-shadow: 0 -0.5vw 2vw rgba(0, 0, 0, 0.05);
}

.nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1vw;
    color: #666;
    font-size: 3vw;
    cursor: pointer;
}

.nav-item i {
    font-size: 5vw;
}

.nav-item.active {
    color: #2196F3;
}

.nav-item.active i {
    transform: scale(1.1);
}

/* 状态颜色样式 */
.indicator-icon.normal {
    background: #e8f5e9;
    color: #4CAF50;
}

.indicator-icon.warning {
    background: #fff3e0;
    color: #ff9800;
}

.indicator-icon.danger {
    background: #ffebee;
    color: #f44336;
}

.status-text.normal {
    background: #e8f5e9;
    color: #4CAF50;
}

.status-text.warning {
    background: #fff3e0;
    color: #ff9800;
}

.status-text.danger {
    background: #ffebee;
    color: #f44336;
}

/* 响应式调整 */
@media screen and (max-width: 320px) {
    .indicator-card {
        padding: 3vw;
    }

    .indicator-icon {
        width: 10vw;
        height: 10vw;
        margin-right: 3vw;
    }

    .indicator-icon i {
        font-size: 5vw;
    }

    .indicator-header h3 {
        font-size: 4vw;
    }

    .indicator-value {
        font-size: 4vw;
    }

    .trend-analysis-btn {
        padding: 1.5vw 3vw;
    }
    
    .trend-analysis-btn span {
        display: none;
    }
    
    .trend-analysis-btn i {
        font-size: 2.8vw;
        margin: 0;
    }
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 8vw;
    color: #666;
}

.loading-container i {
    font-size: 8vw;
    margin-bottom: 4vw;
    color: #2196F3;
}

.loading-container span {
    font-size: 3.5vw;
}
</style>